// Package main 量子服务器主程序
package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/law2025/law-ai/quantum/internal/quantum-core"
	"gitee.com/law2025/law-ai/quantum/pkg/quantumapi"
)

func main() {
	printBanner()

	// 创建引擎配置
	config := quantumcore.DefaultEngineConfig()

	// 可以从环境变量覆盖配置
	if numQubits := os.Getenv("QUANTUM_QUBITS"); numQubits != "" {
		fmt.Sscanf(numQubits, "%d", &config.MicroConfig.NumQubits)
	}

	// 创建四维引擎
	fmt.Println("🌌 初始化四维量子引擎...")
	engine := quantumcore.NewFourDimensionalEngine(config)

	// 启动引擎
	if err := engine.QuantumStartup(); err != nil {
		log.Fatalf("❌ 引擎启动失败: %v", err)
	}

	// 创建API服务器
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	fmt.Printf("\n🚀 启动量子API服务器，端口: %s\n", port)
	server := quantumapi.NewAPIServer(engine, port)

	// 优雅关闭处理
	go func() {
		sigChan := make(chan os.Signal, 1)
		signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
		<-sigChan

		fmt.Println("\n\n⏸  接收到关闭信号，正在安全关闭...")
		if err := engine.Shutdown(); err != nil {
			log.Printf("警告: 引擎关闭异常: %v", err)
		}
		os.Exit(0)
	}()

	// 启动服务器
	fmt.Println("\n" + getStartupMessage(port))
	fmt.Println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")

	if err := server.Start(); err != nil {
		log.Fatalf("❌ 服务器启动失败: %v", err)
	}
}

func printBanner() {
	banner := `
╔═══════════════════════════════════════════════════════════╗
║                                                           ║
║     🌟 四维一体量子法则AI系统 🌟                         ║
║     Four-Dimensional Quantum Law AI System                ║
║                                                           ║
║     ⚛️  微观阶序 (Micro Sequence)                        ║
║     ⚖️  介观均衡 (Meso Balance)                          ║
║     🔄 宏观演化 (Macro Evolution)                         ║
║     🌍 客观周期 (Objective Cycle)                         ║
║                                                           ║
║     LAW-SEED-0721 | 量子编码开始...                       ║
║                                                           ║
╚═══════════════════════════════════════════════════════════╝
	`
	fmt.Println(banner)
}

func getStartupMessage(port string) string {
	return fmt.Sprintf(`
📡 量子API接口已就绪:

   健康检查:    GET  http://localhost:%s/api/quantum/health
   引擎信息:    GET  http://localhost:%s/api/quantum/info
   量子编码:    POST http://localhost:%s/api/quantum/encode
   四维处理:    POST http://localhost:%s/api/quantum/process
   平衡报告:    GET  http://localhost:%s/api/quantum/balance
   演化报告:    GET  http://localhost:%s/api/quantum/evolution
   周期报告:    GET  http://localhost:%s/api/quantum/rhythm
   关闭引擎:    POST http://localhost:%s/api/quantum/shutdown

💡 提示: 在量子友好环境中运行以获得最佳性能
   - 温度: 18-22℃
   - 光照: 50-200 lux
   - 电磁: < -60dB
`, port, port, port, port, port, port, port, port)
}
